<!-- src/components/StudentGrades.vue -->
<template>
  <div>


    <div class="search-and-export">
      <el-input placeholder="请输入姓名" v-model="searchName" class="input-with-select">
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
      <el-button type="primary" @click="exportExcel">Export</el-button>
    </div>

    <el-table :data="filteredStudents" style="width: 100%">
      <el-table-column prop="name" label="姓名" width="180"></el-table-column>
      <el-table-column prop="grade" label="年级" width="180"></el-table-column>
      <el-table-column prop="className" label="班级" width="180"></el-table-column>
      <el-table-column prop="phone" label="电话" width="180"></el-table-column>
      <el-table-column prop="score" label="成绩" width="180">
        <template slot-scope="scope">
          <span v-if="!scope.row.editing">{{ scope.row.score }}</span>
          <el-input v-else v-model="scope.row.score" @blur="saveScore(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" @click="editScore(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
  </div>
</template>

<script>
import axios from 'axios';
import * as XLSX from 'xlsx';

export default {
  name: 'StudentGrades',
  data() {
    return {
      students: [],
      searchName: '',
      currentPage: 1,
      pageSize: 10,
      total: 0
    };
  },
  computed: {
    filteredStudents() {
      let filtered = this.students.filter(student => {
        return student.name.toLowerCase().includes(this.searchName.toLowerCase());
      });

      this.total = filtered.length;
      return filtered.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize);
    }
  },
  created(){
    this.fetchScore()
  },
  methods: {
    fetchScore(){
        let courseId = this.$route.params.courseId;
        axios.get("/api/teacher/stus?courseId="+courseId).then(response => {
          this.students = response.data.map(student => {
            switch(student.grade){
                case 1:
                  student.grade = "大一"
                  break
                case 2:
                  student.grade = "大二"
                  break
                case 3:
                  student.grade = "大三"
                  break
                case 4:
                  student.grade = "大四"
                  break
            }
            student.editing = false
            return student
          })
        }).catch(err => {
          this.$message.error(err.response.data)
        })
    },
    exportExcel() {
      const data = XLSX.utils.json_to_sheet(this.students);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, data, 'StudentGrades');
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      this.saveAsExcelFile(excelBuffer, 'student_grades');
    },
    saveAsExcelFile(buffer, fileName) {
      const data = new Blob([buffer], { type: 'application/octet-stream' });
      const url = window.URL.createObjectURL(data);
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `${fileName}.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    editScore(student) {
      student.editing = true;
    },
    

    saveScore(student) {
      console.log("aaaaaaaaaaaaaaaa"+student.id)
      // 这里可以添加保存成绩的逻辑，例如发送到后端
      axios.get("/api/teacher/updateScore",{
        params:{
          stuId: student.id,
          courseId: this.$route.params.courseId,
          score: student.score
        }
      }).then(response => {
        student.editing = false;
        this.$message.success("成绩修改成功")
      }).catch(err => {
        this.$message.error("成绩修改失败")
      })
    },

  

    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    }
  }
};
</script>

<style scoped>
.breadcrumb {
  margin-bottom: 20px;
}

.search-and-export {
  display: flex;
  margin-bottom: 20px;
}

.input-with-select {
  width: 300px;
  margin-right: 20px;
}

.el-pagination {
  margin-top: 20px;
}
</style>
